package edu.mis.modules.cart;

import com.jfinal.core.Controller;


import java.util.*;

import edu.mis.model.*;

import edu.mis.modules.commodity.CommodityService;
import edu.mis.modules.orderDetail.OrderDetailService;
import edu.mis.modules.orderList.OrderListService;
import edu.mis.modules.seat.SeatService;
import edu.mis.modules.user.UserService;


public class CartController extends Controller {

    static CommodityService commodityService  = new CommodityService();
    static UserService userService  = new UserService();
    static SeatService seatService  = new SeatService();
    static OrderListService orderListService = new OrderListService();
    static OrderDetailService orderDetailService = new OrderDetailService();

    public void index() {
        render("cart.html");
    }

    public void list(){
        User user = userService.findUserByName(getSessionAttr("loginUserName"));
        Cart cart = getSessionAttr("cart");

        if((cart == null)?false:!cart.getItems().isEmpty()) {
            OrderList orders = new OrderList();
            orders.setOrderTime(new Date());
            orders.setUser(user);

            for (Iterator it = cart.getItems().values().iterator(); it.hasNext(); ) {
                OrderDetail orderitem = (OrderDetail) it.next();
                orderitem.setOrderList(orders);
                orders.getOrderDetails().add(orderitem);
            }
            orders.setTotalPrice(cart.getTotalPrice());

            Collection<Object> orderitems = new HashSet<>(0);
            for (Iterator it = orders.getOrderDetails().iterator(); it.hasNext(); ) {
                OrderDetail orderitem = (OrderDetail) it.next();
                Map<String,Object> items = new HashMap<>(0);
                items.put("commodityId",orderitem.getCommodityId());
                items.put("qty",orderitem.getQty());
                items.put("commodityName",orderitem.getCommodity().getCommodityName());
                items.put("price",orderitem.getCommodity().getPrice());
                orderitems.add(items);
            }
            setAttr("orders",orders);
            setAttr("data",orderitems);
            setAttr("result", true);
        }else{
            setAttr("result", false);
            setAttr("msg", "订单为空！");
        }
        setAttr("seat",getSessionAttr("seat"));
        renderJson();
    }

    /**
     * 添加商品视图
     */
    public void add() {
        //render("add.html");  //（默认对应add.html，否则需显性指定，如render("addCommodity.html")）
    }

    public void addToCart() {
        Commodity commodity = commodityService.findCommodityById(getParaToInt("id"));
        OrderDetail orderitem = new OrderDetail();
        orderitem.setCommodity(commodity);
        orderitem.setQty(getParaToInt("qty"));
        Cart cart = (Cart) ((getSessionAttr("cart") == null)?new Cart():getSessionAttr("cart"));
        cart.addCommodity(getParaToInt("id"), orderitem);

        setSessionAttr("cart", cart);
        setAttr("result", true);
        setAttr("msg", "添加成功！");
        renderJson();
    }
    public void updateCart() {
        Cart cart = getSessionAttr("cart");
        cart.updateCart(getParaToInt("id"), getParaToInt("qty"));
        setSessionAttr("cart", cart);
        renderJson();
    }
    public void deleteCart() {
        Cart cart = getSessionAttr("cart");
        cart.removeCommodity(getParaToInt("id"));
        setSessionAttr("cart", cart);
        renderJson();
    }

    public void checkout() {
        User user = userService.findUserByName((String) getSessionAttr("loginUserName"));
        Seat seat = getSessionAttr("seat");
        Cart cart = getSessionAttr("cart");
        if(seat != null) {
            if ((cart == null) ? false : !cart.getItems().isEmpty()) {
                seat.setSeatTypeId(2);
                seat.update();
                OrderList orders = new OrderList();
                orders.setUser(user);
                orders.setSeat(seat);
                orders.setOrderTime(new Date());
                orders.setTotalPrice(cart.getTotalPrice());
                orders.setOrderTypeId(1);
                orderListService.addOrderList(orders);
                orders = orderListService.findOrderListByDate(orders.getOrderTime());
                for (Iterator it = cart.getItems().values().iterator(); it.hasNext(); ) {
                    OrderDetail orderitem = (OrderDetail) it.next();
                    orderitem.setOrderList(orders);
                    orderDetailService.addOrderDetail(orderitem);
                    orders.getOrderDetails().add(orderitem);
                }
                setAttr("result", true);
                setAttr("msg", "提交订单成功!");
                cart.clearCart();
                setSessionAttr("cart", cart);
            } else{
                setAttr("result", false);
                setAttr("msg", "提交失败，订单为空!");
            }
        }else{
            setAttr("result",false);
            setAttr("msg", "提交失败，请选择餐桌!");
        }
        removeSessionAttr("seat");
        renderJson();
    }
    public void clearCart() {
        Cart cart = getSessionAttr("cart");
        cart.clearCart();
        setSessionAttr("cart", cart);
        setAttr("result", true);
        setAttr("msg", "清空成功！");
        renderJson();
    }
    public void view_assignSeat(){
        setAttr("seat",Seat.dao.findAllUnusedSeats());//分配前得到所有餐桌
        render("assignSeat.html");
    }
    public void assignSeat(){
        Seat seat = seatService.findSeatById(getParaToInt("seatId"));

        setSessionAttr("seat", seat);
        if(seat != null){
            setAttr("result", true);
            setAttr("msg", "餐桌分配成功!");
        }else{
            setAttr("result", false);
            setAttr("msg", "餐桌分配失败!");
        }
        renderJson();
    }



}
